<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import {
  ReportQueryForm,
  ReportSearchConditionVO,
  ReportSearchResultVO
} from "@/api/types";
import type { FamilyInfoVO } from "@/api/types/user";
import { getFamilyInfo } from "@/api/user";
import { PAGE_SIZE } from "@/constants/common-const";
import { ArrowLeft, Loading, Search } from "@element-plus/icons-vue";
import { ElMessage, TabsPaneContext } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { attentionTypeList as commonAttentionTypeList } from "@/utils/tools";

import dayjs from "dayjs";

// import AddTask from "@/components/AddTask/index.vue";
import Jiankang from "@/components/jiankang/index.vue";
import FollowDialog from "@/views/followUpPlan/components/followDialog.vue";
import ReportCompareDrawer from "./components/report-compare-drawer/index.vue";

defineOptions({
  name: "Family"
});

const route = useRoute();
const router = useRouter();
const attentionTypeList = ref(commonAttentionTypeList);

// 当前选中的标签页
const activeTab = ref("all");
const showCompareDrawer = ref(false);
const currentReport = ref<ReportSearchResultVO>();

// 家庭信息和标签页数据
const familyInfo = ref<FamilyInfoVO[]>([]);
const tabsData = ref([{ name: "all", label: "全部" }]);

// 查询表单初始状态
const queryFormState: ReportQueryForm = {
  userName: "",
  startDate: null,
  endDate: null,
  riskLevelId: null as number | null,
  healthCategoryId: null as number | null,
  statusId: null as number | null,
  attentionType: null as number | null,
  medicalInstitution: null,
  healthTagId: null as number | null,
  familyId: null as number | null,
  pageNum: 1,
  pageSize: PAGE_SIZE
};

// 响应式数据
const queryForm = reactive({ ...queryFormState });
const dictData = ref<ReportSearchConditionVO>({});
const dateRange = ref([]);

// 表格数据
const tableData = ref<ReportSearchResultVO[]>([]);

const total = ref(2);
const tableLoading = ref(false);
// const addTaskDrawerRef = ref();
const addTaskDialogVisible = ref();
const addJKDrawerRef = ref();

// 获取家庭信息并生成标签页数据
async function loadFamilyInfo() {
  try {
    const familyId = Number(route.query.familyId);
    if (!familyId) {
      ElMessage.error("缺少家庭ID参数");
      return;
    }

    // 设置查询表单的familyId
    queryForm.familyId = familyId;

    const response = await getFamilyInfo({ familyId });
    if (response?.data) {
      familyInfo.value = Array.isArray(response.data)
        ? response.data
        : [response.data];

      // 生成标签页数据
      tabsData.value = [
        { name: "all", label: "全部" },
        ...familyInfo.value.map((member, index) => ({
          name: `member_${member.userId || index}`,
          label: member.displayName || `成员${index + 1}`
        }))
      ];
    }
  } catch (err) {
    console.error("获取家庭信息失败:", err);
    ElMessage.error("获取家庭信息失败");
  }
}

// 获取字典数据
async function queryDictionaryData() {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      dictData.value = response.data;
    }
  } catch (err) {
    console.error("获取字典数据失败:", err);
    ElMessage.error("获取字典数据失败");
  }
}

// 查询报告列表
async function queryReportList() {
  tableLoading.value = true;
  try {
    const response = await reportApi.queryReportList({
      ...queryForm,
      endDate: queryForm.endDate ? dayjs(queryForm.endDate).valueOf() : null,
      startDate: queryForm.startDate
        ? dayjs(queryForm.startDate).valueOf()
        : null
    });
    if (response?.data) {
      tableData.value = (response.data.list || []).map(item => ({
        ...item,
        id: item.reportId
      }));
      total.value = response.data.total || 0;
    }
  } catch (err) {
    console.error("查询报告列表失败:", err);
    ElMessage.error("查询报告列表失败");
  } finally {
    tableLoading.value = false;
  }
}

// 搜索
function onSearch() {
  queryForm.pageNum = 1;
  queryReportList();
}

// 重置
function onReload() {
  const currentFamilyId = queryForm.familyId;
  Object.assign(queryForm, queryFormState);
  queryForm.familyId = currentFamilyId; // 保持当前的familyId
  dateRange.value = [];
  activeTab.value = "all"; // 重置到全部标签页
  queryReportList();
}

// 日期范围变化
function onDateChange(dates) {
  if (dates && dates.length === 2) {
    queryForm.startDate = dates[0];
    queryForm.endDate = dates[1];
  } else {
    queryForm.startDate = null;
    queryForm.endDate = null;
  }
}

// 标签页切换
const handleTabClick = (tab: TabsPaneContext) => {
  activeTab.value = tab.paneName as string;

  // 根据标签页筛选数据
  if (activeTab.value === "all") {
    // 显示所有家庭成员的数据 - 清空用户名筛选
    queryForm.userName = "";
  } else {
    // 根据选中的标签页找到对应的家庭成员
    const memberIndex = tabsData.value.findIndex(
      t => t.name === activeTab.value
    );
    if (memberIndex > 0) {
      // 跳过"全部"标签页，通过用户名筛选特定成员
      const member = familyInfo.value[memberIndex - 1];
      queryForm.userName = member?.displayName || "";
    }
  }

  queryForm.pageNum = 1;
  queryReportList();
};

// 查看报告
function viewReport(reportId: number | string) {
  router.push({
    path: "/report/detail",
    query: { reportId, mode: "view" }
  });
}

// 报告对比
function compareReport(report: any) {
  console.log("showCompareDrawer", showCompareDrawer.value, report);
  showCompareDrawer.value = true;
  currentReport.value = report;
}

// 填写建议
function writeSuggestion(reportId: number | string) {
  // router.push({
  //   path: "/system/report/suggestion",
  //   query: { reportId }
  // });
  addJKDrawerRef.value?.open(reportId);
}

// 加入任务
function addToTask(reportId: number | string) {
  // addTaskDrawerRef.value?.open(reportId);
  addTaskDialogVisible.value = true;
  // ElMessageBox.confirm("确认将此报告加入任务列表吗？", "确认操作", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning"
  // })
  //   .then(() => {
  //     console.log("加入任务:", reportId);
  //     ElMessage.success("已成功加入任务列表");
  //   })
  //   .catch(() => {
  //     // 用户取消操作
  //   });
}

// 分页大小变化
function handleSizeChange(size: number) {
  queryForm.pageSize = size;
  queryForm.pageNum = 1;
  queryReportList();
}

// 当前页变化
function handleCurrentChange(page: number) {
  queryForm.pageNum = page;
  queryReportList();
}

// 返回上一页
const goBack = () => {
  router.back();
};

const splitBracketText = (
  input: string
): { outside: string; inside: string } => {
  const match = input.match(/^([^\(]+)\(([^)]+)\)$/);
  if (match) {
    return {
      outside: match[1].trim(),
      inside: match[2].trim()
    };
  } else {
    // 没有匹配的情况：返回原字符串为 outside，inside 为空
    return {
      outside: input.trim(),
      inside: ""
    };
  }
};

function onAddTaskSave(data) {
  console.log("保存健康信息:", data);
  ElMessage.success("添加随访计划成功");
}

function onJKSave(data) {
  console.log("保存健康信息:", data);
  ElMessage.success("添加随访计划成功");
}

onMounted(() => {
  loadFamilyInfo();
  queryDictionaryData();
  queryReportList();
});
</script>

<template>
  <div class="min-h-screen pr-5 common-page">
    <!-- 头部导航 -->
    <div class="bg-white sticky top-0 z-10">
      <div class="flex items-center py-3">
        <el-button :icon="ArrowLeft" text class="!p-2 mr-2" @click="goBack" />
        <span class="text-lg font-medium">家庭报告</span>
      </div>
    </div>

    <!-- 标签页 -->
    <div class="bg-white">
      <el-tabs v-model="activeTab" class="px-6" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="tab in tabsData"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name"
        />
      </el-tabs>
    </div>

    <!-- 搜索表单 -->
    <div class="bg-white mx-6">
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item class="w-60">
          <el-input
            v-model="queryForm.userName"
            :prefix-icon="Search"
            clearable
            placeholder="搜索用户"
          />
        </el-form-item>

        <el-form-item class="w-80">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="onDateChange"
          />
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.riskLevelId"
            clearable
            placeholder="请选择风险等级"
          >
            <el-option
              v-for="item in dictData.riskLevelList || []"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.healthCategoryId"
            clearable
            placeholder="请选择健康分类"
          >
            <el-option
              v-for="item in dictData.healthCategoryList || []"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.statusId"
            clearable
            placeholder="请选择状态类型"
          >
            <el-option
              v-for="item in dictData.healthStatusList || []"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.attentionType"
            clearable
            placeholder="请选择关注类型"
          >
            <el-option
              v-for="item in attentionTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.medicalInstitution"
            clearable
            placeholder="请选择机构/医院"
          >
            <el-option
              v-for="item in dictData.medicalInstitutionList || []"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="w-60">
          <el-select
            v-model="queryForm.healthTagId"
            clearable
            placeholder="请选择健康标签"
          >
            <el-option
              v-for="item in dictData.healthTagList || []"
              :key="item.tagId"
              :label="item.name"
              :value="item.tagId"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="onReload">重置</el-button>
          <el-button type="primary" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 报告列表 -->
    <div class="px-2 py-4">
      <!-- 加载状态 -->
      <div v-if="tableLoading" class="text-center py-12">
        <el-icon class="is-loading text-2xl text-blue-500 mb-2">
          <Loading />
        </el-icon>
        <div class="text-gray-500">加载中...</div>
      </div>

      <div v-else class="relative">
        <div class="h-full w-0.5 absolute left-[19px] top-2 bg-[#297f8017]" />
        <div v-for="item in tableData" :key="item.reportId" class="mb-6 ml-12">
          <!-- 日期标题 -->
          <div class="flex items-center mb-3 text-gray-600 text-sm">
            <!-- <el-icon class="mr-2 text-blue-500"><Calendar /></el-icon> -->
            <div
              class="w-2 h-2 rounded-full border-2 border-blue-400 absolute left-4"
            />
            {{ item.inspectionDate }}
          </div>

          <!-- 报告卡片 -->
          <div
            class="bg-white border rounded-lg p-5 shadow-sm hover:shadow-md transition-shadow relative"
          >
            <!-- 用户信息和标签 -->
            <div class="mb-4">
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center gap-3">
                  <span class="text-base font-medium text-gray-900">{{
                    splitBracketText(item.userName).outside
                  }}</span>
                  <div
                    class="text-xs bg-[#daf4ff] text-[#125981] font-bold py-1 px-2 rounded-lg"
                  >
                    {{ splitBracketText(item.userName).inside }}
                  </div>
                  <div
                    v-if="item.healthCategory"
                    :class="[
                      'text-xs',
                      'font-bold py-1 px-2 rounded-lg',
                      item.healthCategory === '健康人群'
                        ? 'bg-[#C4F29F]'
                        : item.healthCategory === '亚健康人群'
                          ? 'bg-[#FFE281]'
                          : 'bg-[#FFE281]'
                    ]"
                  >
                    {{ item.healthCategory }}
                  </div>
                </div>
                <!-- 状态标签 -->
                <div
                  :class="`p-0.5 border-1  rounded-tr-lg rounded-bl-lg absolute right-0 top-0  text-xs ${item.reportStatusName === '已通过' ? 'border-[#44D7B6] bg-[#C9FFF3]' : 'border-[#FFB634] bg-[#FFF1C4]'}`"
                >
                  {{ item.reportStatusName }}
                </div>
              </div>
              <div class="flex justify-between items-center">
                <div class="text-gray-500 text-sm">
                  {{ item.institution }} | 体检报告：{{ item.inspectionDate }}
                </div>
                <!-- <el-rate
                  :model-value="Math.min(Math.ceil(item.attentionLevel / 5), 5)"
                  disabled
                  size="large"
                /> -->
                <EditableRate
                  v-model="item.attentionLevel"
                  :data-type="1"
                  :data-id="item.reportId"
                />
              </div>
            </div>

            <el-divider />

            <!-- 风险信息 -->
            <div class="mb-4">
              <div class="flex flex-wrap gap-2 mb-3">
                <div
                  v-for="indicator in item.abnormalIndicators"
                  :key="indicator.name"
                  class="text-sm py-1 px-3 bg-[#FFF2F4] rounded-xl"
                >
                  {{ indicator.name }}
                </div>
              </div>
              <div class="flex items-center mb-2">
                <span class="text-gray-600 mr-2">风险：</span>
                <div
                  :class="{
                    'riskLevel-tag': true,
                    'riskLevel-tag--sub': item.riskLevel === '良好',
                    'riskLevel-tag--normal': item.riskLevel === '轻度风险',
                    'riskLevel-tag--chronic':
                      item.riskLevel === '高风险' ||
                      item.riskLevel === '中高风险' ||
                      item.riskLevel === '中度风险'
                  }"
                  size="small"
                >
                  {{ item.riskLevel }}
                </div>
              </div>
              <div class="text-gray-600 text-sm leading-relaxed">
                <!-- {{ item.abnormalIndicators }} -->
              </div>
            </div>

            <el-divider />

            <!-- 操作按钮 -->
            <div class="flex flex-wrap gap-4">
              <el-button type="primary" link @click="viewReport(item.reportId)">
                查看报告
              </el-button>
              <el-button type="primary" link @click="compareReport(item)">
                报告对比
              </el-button>
              <el-button
                type="primary"
                link
                @click="writeSuggestion(item.reportId)"
              >
                写建议
              </el-button>
              <el-button type="primary" link @click="addToTask(item.reportId)">
                加入任务
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="flex justify-end mt-6">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 空状态 -->
      <div
        v-if="!tableLoading && tableData.length === 0"
        class="text-center py-12"
      >
        <div class="text-gray-400 text-lg mb-2">暂无数据</div>
        <div class="text-gray-400 text-sm">请尝试调整搜索条件</div>
      </div>
    </div>

    <ReportCompareDrawer
      v-model="showCompareDrawer"
      :current-report="currentReport"
    />
    <!-- <AddTask
      ref="addTaskDrawerRef"
      title="添加随访计划"
      @save="onAddTaskSave"
    /> -->

    <!-- 任务计划弹窗 -->
    <follow-dialog
      v-model:visible="addTaskDialogVisible"
      :mode="'create'"
      :task-data="[]"
    />
    <Jiankang ref="addJKDrawerRef" title="健康建议" @save="onJKSave" />
  </div>
</template>
